package com.chao.base.io.socketio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class BioSocketDemo {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(9000);
            while (true) {
                System.out.println("等待客户端连接");
                Socket cilentSocket = serverSocket.accept();
                System.out.println("有客户端连接了");
                handler(cilentSocket);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private static void handler(Socket socket) {
        byte[] buffer = new byte[1024];
        try {
            int read = socket.getInputStream().read(buffer);
            System.out.println("read完成");
            if (read != -1) {
                System.out.println("接收到客户端发送的消息" + new String(buffer, 0, read));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
